import { Color, Texture2D } from "cc";
import * as PNG from "@vivaxy/png"

export class Texture2DWrapper {

    private _texture: Texture2D = null!;
    public get texture(): Texture2D {
        return this._texture;
    }
    public set texture(value: Texture2D) {
        this._texture = value;
    }

    constructor(width: number, height: number, format: number) {

        this._texture = new Texture2D()
        this._texture.reset({
            width: width,
            height: height,
            format: format,
            mipmapLevel: 1,
            baseLevel: 0,
            maxLevel: 100
        })
    }

    uploadData(data: HTMLCanvasElement | HTMLImageElement | ArrayBufferView | ImageBitmap) {
        this.texture.uploadData(data);
    }


    static encodeToPNG(texture: Texture2D): Uint8Array | null {

        const png = PNG.encode({
            width: texture.width,
            height:  texture.height,
            data: Array.from(texture.image?._nativeAsset as Uint8Array),
            depth: 16,
            compression: 0,
            interlace: 0,
            colorType: 2,
            filter: 0,
            gamma: 1,
        });

        return png;
    }

    /**
     * 将纹理转换为32位像素数组
     * @param texture 
     */
    static getPixels32(texture: Texture2D): Color[] {
        const data = texture.image?._nativeAsset;
        const colors: Color[] = [];
        if (data) {
            const pixels = new Uint8Array(data);
            for (let i = 0; i < pixels.length; i += 4) {
                const r = pixels[i];
                const g = pixels[i + 1];
                const b = pixels[i + 2];
                const a = pixels[i + 3];
                colors.push(new Color(r, g, b, a));
            }

        }
        return colors;
    }


}